package com.valuegroup.smarttodo.data.service;

import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.SumTopic;
import com.valuegroup.smarttodo.data.model.SumTopicDao;

import java.util.Date;
import java.util.List;

public class SumTopicService extends BaseService {

    public SumTopic addSumTopic(String topic) {
        SumTopic t = getDefaultSumTopic();
        t.setTitle(topic);
        getSumTopicDao().save(t);
        return t;
    }

    public List<SumTopic> findSumTopicOnUsable() {
        return getSumTopicDao().queryBuilder()
                .where(SumTopicDao.Properties.Usable.eq(true))
                .where(SumTopicDao.Properties.Status.eq(AppStatus.Status.NORMAL))
                .orderAsc(SumTopicDao.Properties.Sort)
                .list();
    }

    public List<SumTopic> findSumTopic() {
        return getSumTopicDao().queryBuilder()
                .where(SumTopicDao.Properties.Status.eq(AppStatus.Status.NORMAL))
                .orderAsc(SumTopicDao.Properties.Sort)
                .list();
    }

    public SumTopic getDefaultSumTopic() {
        SumTopic t = new SumTopic();
        t.setSort(getSumTopicDao().loadAll().size());
        t.setTitle("");
        t.setUsable(true);
        t.setCreatedDt(new Date());
        t.setUpdatedDt(t.getCreatedDt());
        t.setStatus(AppStatus.Status.NORMAL);
        return t;
    }

    public SumTopic addTopic(String text) {
        List<SumTopic> exist = getSumTopicDao().queryBuilder()
                .where(SumTopicDao.Properties.Title.eq(text))
                .where(SumTopicDao.Properties.Status.eq(AppStatus.Status.NORMAL))
                .list();
        SumTopic topic;
        if (exist != null && exist.size() > 0) {
            topic = exist.get(0);
            if (!topic.getUsable()) {
                topic.setUsable(true);
                topic.setUpdatedDt(topic.getCreatedDt());
                getSumTopicDao().update(topic);
            }
        } else {
            topic = getDefaultSumTopic();
            topic.setTitle(text);
            getSumTopicDao().save(topic);
        }
        return topic;
    }

}
